import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Station, StationDocument } from '@/schema/station.schema';
import axios from 'axios';
import dayjs from 'dayjs';

@Injectable()
export class StationService {
  constructor(
    @InjectModel(Station.name) private stationModel: Model<StationDocument>
  ) {}

  async insertMany() {
    const stationRes = await axios.get(
      `https://kyfw.12306.cn/otn/resources/js/framework/station_name.js?station_name=${dayjs().valueOf()}`
    );

    const station_names = stationRes.data.match(
      /station_names\s*=\s*([^;]+);/
    )[1];

    const arr = station_names.replace(/['"]/g, '').split('@');
    const results = [];
    arr
      .filter((v) => v !== '')
      .forEach((station) => {
        const initial = station.split('|')[0];
        const name = station.split('|')[1];
        const code = station.split('|')[2];
        const fullPinyin = station.split('|')[3];
        const shortPinyin = station.split('|')[4];
        const sort = station.split('|')[5];
        const areaNo = station.split('|')[6];
        const areaName = station.split('|')[7];
        results.push({
          initial,
          name,
          code,
          fullPinyin,
          shortPinyin,
          sort,
          areaNo,
          areaName
        });
      });
    this.stationModel.insertMany(results);
  }

  async refresh() {
    await this.stationModel.deleteMany(); //删掉全部数据
    this.insertMany();
  }
}
